// pages/xiadan/xiadan.js
var app = getApp()
var url = app.globalData.url
var address = {}
var menuName1 = ""
var menuName2 = ""
var page = 0
var friendId = "x"
var menuId=""
var eqBrand = '' // 品牌
var eqType = "" //类型
var eqModel = "64G" //型号
var eqColor = "#FFF"
var smenuid=""
var brandId=''
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mainmenus: [{}, {}, {}, {}, {
      menuId: 0,
      menuIcon: '',
      menuName: "常用服务"
    }],
    secmenus: [0, 0],
    names: "代报修",
    flag: true,
    toolIndex: 0,
    showPop: true,
    location: "",
    tabIndex: 0,
    selectIndex: 1,
    friends: [1,2,3],
    page1: 0,
    page2: 1,
    addIndex1: 0,
    addIndex: 0,
    colorIndex:0,
    neicunindex:0
  },

  choseterm(e) {
    const that = this

    that.setData({
      tabIndex: e.currentTarget.id
    })

  },
  back() {
    wx.navigateBack(1)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const that = this
    that.getMenuList()
    that.getFriends(1)
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR - 180;
        console.log(calc)
        that.setData({
          winHeight: calc
        });
      }
    });
  },
  getDetails1(e){
    console.log(e)
    this.setData({
      euipIndex1:e.currentTarget.dataset.index
    })
  },
  getDetails(e) {
    this.setData({
      euipIndex: e.currentTarget.dataset.index
    })
  },
  nextBtn(e) {
    page = page + 1
    this.setData({
      page1: page + 1,
      page2: page + 1
    })
    this.getFriends(page)
  },
  proBtn(e) {
    if (page > 0) {
      page = page - 1
      this.setData({
        page1: page,
        page2: page
      })
      this.getFriends(page)
    } else {
      wx.showToast({
        title: '已经最前',
        icon: "loading",
        duration: 1000
      })
    }

  },
  phoneCat() {
    wx.navigateTo({
      url: "../equipment/equipment?page=myaddr&index=4&selectAddress=true"
    })
  },
  selectMenu(e) {
    menuName2 = e.currentTarget.dataset.name
    menuId = e.currentTarget.id
    this.setData({
      menuIndex: e.currentTarget.dataset.index
    })
    this.getEquipment(menuId,friendId)
    this.getpictures()
  },
  getMenuList() {
    const that = this
    wx.request({
      url: url + '/menu/menus_one',
      data: {},
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        console.log("获取一级菜单：")
        console.log(res.data)

        if (res.data.code == 1) {
          res.data.data.menus.push({
            menuId: 0,
            "menuIcon": {
              "menuIconChecked": "../image/icon05.png",
              "menuIconUnChecked": "../image/icon05.png",
              "firstColor": "",
              "lastColor": ""
            },
            menuName: "常用服务"
          })
          menuName1 = res.data.data.menus[0].menuName
          that.setData({
            mainmenus: res.data.data.menus
          })
          console.log("赋值后的mainmenus：")
          //  console.log(this.data.mainmenus)
          that.getsecond(res.data.data.menus[0].menuId)
        } else {
          wx.showToast({
            title: '加载失败',
            icon: "loading",
            duration: 1000
          })
        }

      }

    })
  },
  getsecond(data) {
    const that = this

    wx.request({
      url: url + '/menu/menus_pid',
      data: {
        pid: data
      },
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        console.log("获取二级菜单：")
        console.log(res.data)

        if (res.data.code == 1) {
          menuName2 = res.data.data.menus[0].menuName
          menuId = res.data.data.menus[0].menuId
          that.getEquipment(menuId, friendId)
          that.getpictures()
          that.setData({
            secmenus: res.data.data.menus,
            menuIndex: 0
          })
        } else {
          that.setData({
            secmenus: []
          })
          wx.showToast({
            title: '暂无数据',
            icon: "loading",
            duration: 1000
          })
        }
      }
    })
  },
  // 常用服务
  getUral() {
    const that = this
    wx.request({
      url: url + '/menu/menu_commonly_used',
      data: {},
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        console.log("获取常用服务：")
        console.log(res.data)

        if (res.data.code == 1) {
          that.setData({
            menuUral: res.data.data.menu
          })
        } else {
          wx.showToast({
            title: '加载失败',
            icon: "loading",
            duration: 1000
          })
        }

      }

    })
  },
  popupTap() {
    let popupComponent = this.selectComponent('.J_Popup');

    popupComponent && popupComponent.toggle(false);
  },
  popupTap1() {
    let popupComponent = this.selectComponent('.J_Popup1');

    popupComponent && popupComponent.toggle(false);
  },
  tosecMenu(e) {
    var id = e.currentTarget.id
    const that = this
    menuName1 = e.currentTarget.dataset.name
    that.getsecond(id)
    that.sildeOut()
    setTimeout(function() {
      that.fadeOut()
    }, 500)
    that.setData({
      toolIndex: e.currentTarget.dataset.index
    })

  },
  getMenus(e) {
    menuName1 = e.currentTarget.dataset.name1
    menuName2 = e.currentTarget.dataset.name2
    menuId = e.currentTarget.id
    this.popupTap()
    this.getEquipment(menuId, friendId)
  },
  showPop() {
    this.showPopup()

    this.setData({
      showPop: true
    })
    this.getUral()
  },
  showPop2() {
    this.showPopup()
    this.setData({
      showPop: false,
      menuNames: menuName1 + menuName2
    })
  },
  showPopup() {
    let popupComponent = this.selectComponent('.J_Popup');
    /*popupComponent && popupComponent.show();*/
    popupComponent && popupComponent.toggle(true);
  },
  hidePopup() {
    let popupComponent = this.selectComponent('.J_Popup');
    //popupComponent && popupComponent.hide();
    popupComponent && popupComponent.toggle();
  },
  showPopup1() {
    let popupComponent = this.selectComponent('.J_Popup1');
    /*popupComponent && popupComponent.show();*/
    popupComponent && popupComponent.toggle(true);
  },
  hidePopup1() {
    let popupComponent = this.selectComponent('.J_Popup1');
    //popupComponent && popupComponent.hide();
    popupComponent && popupComponent.toggle();
  },
  // 菜单事件
  sildeOut() {
    var animation = wx.createAnimation({
      duration: 100,
      timingFunction: "liner",
      delay: 0
    })
    this.animation = animation
    animation.translateX(800).opacity(0).step().translateX(-800).step()
    this.setData({
      animation: animation.export(),
    })
  },
  fadeOut() {
    var animation = wx.createAnimation({
      duration: 100,
      timingFunction: "liner",
      delay: 0
    })
    this.animation = animation
    animation.opacity(1).translateX().step()
    this.setData({
      animation: animation.export(),
    })

  },
  xiadan() {
    const that = this
    var user = wx.getStorageSync("user")
    wx.showLoading({
      title: '正在下单',
    })
    wx.request({
      url: 'https://zanwei.mynatapp.cc/sell/orders/yiJIan',
      data: {
        usesAccount: user.wxUsersAccount,
        addressName: address.addressName,
        addressTel: address.addressPhone,
        addressLocal: address.addressLocation,
        longitude: longitude,
        latitude: latitude,
        Service: menuName2 + menuName1
      },
      header: {
        "contentType": "application/json"
      },
      success(res) {
        if (res.data.code === 1) {
          wx.hideLoading()
          app.globalData.curentTab=4
          wx.navigateTo({
            url: '../order/order',
          })
        }
      },
    })
  },
  selectAddr() {
    var that = this;

    wx.getSetting({
      success: (res) => {
        console.log(res);
        console.log(res.authSetting['scope.userLocation']);
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) { //非初始化进入该页面,且未授权
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则下单等功能将无法使用',
            success: function(res) {
              if (res.cancel) {
                console.info("授权失败");

              } else if (res.confirm) {
                //village_LBS(that);
                wx.openSetting({
                  success: function(data) {
                    console.log(data);
                    if (data.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 5000
                      })
                      //再次授权，调用getLocationt的API

                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'success',
                        duration: 5000
                      })
                    }
                  }
                })
              }
            }
          })
        }
      }
    })

    wx.chooseLocation({
      success: function(s) {
        console.log(s)
        addr.addressLocation = s.address
        longitude = s.longitude
        latitude = s.latitude
        that.setData({
          location: s.address
        })
      },
    })

  },
  getName(e) {
    console.log(e)
    addr.addressName = e.detail.value
  },
  getPhone(e) {
    addr.addressPhone = e.detail.value
  },
  getAddrDoornumber(e) {
    addr.addressDoorNumber = e.detail.value
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    app.editTabBar()
    const that = this
    var address1 = wx.getStorageSync("address")
    console.log("onshow")
    console.log(address)
    if (address1.addressDoorNumber != undefined) {
      address = address1
      that.setData({
        addressName: address.addressName,
        addressTel: address.addressPhone,
        location: address.addressLocation
      })
    } else {
      that.getDefaultAddr()
    }
  },
  // 获取默认地址
  getDefaultAddr(id) {
    console.log(id)
    const that = this
    var user = wx.getStorageSync("user")
    wx.request({
      url: url + '/address/default_address',
      method: "get",
      header: {
        "content-type": "application/json"
      },
      data: {
        usersTel: user.wxUsersAccount
      },
      success(res) {
        console.log(res.data)
        if (res.data.code == 1) {
          address = res.data.data.address
          that.setData({
            addressName: address.addressName,
            addressTel: address.addressPhone,
            location: address.addressLocation
          })
        } else {

        }
      }
    })
  },
  // 亲友号
  getFriends(page) {
    const that = this
    var user = wx.getStorageSync("user")
    wx.request({
      url: url + '/relatives_friends/select_page',
      method: "get",
      header: {
        "content-type": "application/json"
      },
      data: {
        number: user.wxUsersAccount,
        page: page //第几页
      },
      success(res) {
        console.log("亲友号")
        console.log(res.data)
        if (res.data.code == 1) {
          var f = res.data.data.relativesFriendsList1
          friendId = f[0].wxUsers.wxUsersAccount
          that.setData({
            friends:f,
            selectIndex:0
          })
        } else {

        }
      }
    })
  },
  selectedThis(e) {

    this.setData({
      selectIndex: e.currentTarget.dataset.idx
    })
    friendId = e.currentTarget.dataset.id
  },
  //设备管理
  getEquipment(menuid, mid) { //电脑4 手机5 家电6 办公7
    const that = this
   if(mid=='x'||mid==''){
    //  wx.showToast({
    //    title: '请选择亲友号',
    //    icon:"loading",
    //    duration:1000
    //  })
   }else{
    wx.request({
      url: url + '/Equipment/getListEquipment',
      data: {
        account: friendId,
        menuId: menuid
      },
      header: {
        "content-type": "application/json"
      },
      success(res) {
        console.log(res.data)
        if (res.data.code == 1) {
          if (menuid == 4) {
            that.setData({
              computers: res.data.data.equipment
            })
          } else if (menuid == 5) {
            that.setData({
              phones: res.data.data.equipment
            })
          } else if (menuid == 6) {
            that.setData({
              jiadian: res.data.data.equipment
            })
          } else if (menuid == 7) {

          }

        } else {
          if (menuid == 4) {
            that.setData({
              computers: []
            })
          } else if (menuid == 5) {
            that.setData({
              phones: []
            })
          } else if (menuid == 6) {
            that.setData({
              jiadian: []
            })
          }
        }
      }
    })
   }
  },
  //设备类型添加设备的
  getShebeiType(data) {
    const that = this
    wx.request({
      url: url + '/menu/menus_pid',
      data: {
        pid: data
      },
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        console.log("获取二级菜单：")
        console.log(res.data)

        if (res.data.code == 1) {
          smenuid = res.data.data.menus[0].menuId
          eqType = res.data.data.menus[0].menuName
          that.setData({
            types: res.data.data.menus,
            eqtype:eqType
          })
          if (data != 5) {
            that.setData({
              checkedimg1: res.data.data.menus[0].menuImg1
            })
          }
          that.getbrans(res.data.data.menus[0].menuId,data)
        } else {
          wx.showToast({
            title: '加载失败',
            icon: "loading",
            duration: 1000
          })
        }
      }
    })
  },
  //加载品牌类型
  getbrans(data,id) {
    const that = this
    wx.request({
      url: url + '/menu/menus_pid',
      data: {
        pid: data
      },
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        console.log("获取品牌类型：")
        console.log(res.data)

        if (res.data.code == 1) {
          eqBrand = res.data.data.menus[0].menuName
          brandId = res.data.data.menus[0].menuId
          that.setData({
            brans: res.data.data.menus,
            eqbrand:eqBrand
          })
          if (id == 5) {
            that.setData({
              checkedimg1: res.data.data.menus[0].menuImg1,
              checkedimg2:''
            })
          } else {
            that.setData({
              checkedimg2: res.data.data.menus[0].menuImg1
            })
          }
        } else {
          eqBrand = ''
          eqModel = ''
          that.setData({
            brans: [],
            models: [],
            isTrue: false
          })
        }
      }
    })
  },
  addequipment(e) {
    if(friendId==''){
      wx.showToast({
        title: '请先选中亲友号',
        icon:"loading"
      })
    }else{
      this.showPopup1()
      console.log(e)
      menuId = e.currentTarget.id
      this.getShebeiType(menuId)
      this.getpictures()
      this.setData({
        equipmentShow: menuId,
        pcolor: "白色",
        pmodel: "64G"
      })
    }
  
  },
  getpictures() {
    const that = this
    wx.request({
      url: url + '/menu/menus_icon',
      data: {
        mid: menuId
      },
      header: {
        "content-type": "application/json"
      },
      success(res) {
        console.log("查询图片")
        console.log(res)
        if (res.data.code == 1) {
          that.setData({
            imgs: res.data.data.icon
          })
        }
      }

    })
  },
  selectRank(e) {
    const that = this
    smenuid = e.currentTarget.dataset.sid
    eqType = e.currentTarget.dataset.type
    that.getbrans(e.currentTarget.dataset.sid)
    that.setData({
      addIndex: e.currentTarget.dataset.index,
      eqtype: eqType,
      checkedimg1: e.currentTarget.dataset.img
    })
  },
  selectBrand(e) {
    const that = this
    console.log("选择品牌时")
    console.log(e)
    const type = e.currentTarget.dataset.type
    brandId = e.currentTarget.dataset.id
    if (type) {
      that.setData({
        checkedimg1: e.currentTarget.dataset.img
      })
    } else {
      that.setData({
        checkedimg2: e.currentTarget.dataset.img
      })
    }
    eqBrand = e.currentTarget.dataset.brand
    that.setData({
      addIndex1: e.currentTarget.dataset.index,
      eqbrand: eqBrand

    })
  },


  getModels(e) {
    const that = this
    eqModel = e.currentTarget.dataset.name
    that.setData({
      neicunindex: e.currentTarget.dataset.index,
      pmodel: eqModel
    })
  },
  getColor(e) {
    const that = this
    var color = e.currentTarget.dataset.name

    if (color == "#fff") {
      eqColor = "白色"
    } else if (color == "#000") {
      eqColor = "黑色"
    } else if (color == "#ECE2AD") {
      eqColor = "金色"
    } else if (color == "#EFB2E1") {
      eqColor = "粉色"
    }
    that.setData({
      colorIndex: e.currentTarget.dataset.index,
      pcolor: eqColor
    })
  },
  //确认添加设备
  submitAddsb() {
    const that = this
     if(friendId.length==0){
       wx.showToast({
         title: '请选择亲友号',
         icon:"loading",
         duration:1000
       })
     }else
    console.log(eqBrand == null)
    if (eqBrand == '') {
      wx.showToast({
        title: '请选择品牌类型',
        icon: "loading",
        duration: 1000
      })
    } else {
      wx.request({
        url: url + '/Equipment/addEquipment',
        data: {
          wxUsersAccount: friendId,
          menuId: menuId,
          typeId: smenuid,
          eqType: eqType,
          eqBrand: eqBrand,
          eqModel: eqModel,
          eqColor: eqColor,
          brandId: brandId
        },
        method: "get",
        header: {
          "content-type": "application/json"
        },
        success(res) {
          console.log(res)
          if (res.data.code == 0) {
            wx.showToast({
              title: '添加成功',
              icon: "success",
              duration: 1000
            })
            that.popupTap1()
            that.getEquipment(menuId,friendId)
          } else {
            wx.showToast({
              title: '添加失败',
              icon: "success",
              duration: 1000
            })
          }
        }
      })
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})